<?php
/**
 *Create by PhpStorm
 *User:Kendy
 *Date:2019/10/12/010
 *Time:10:49
 */
namespace app\common\model;
use think\Model;
use think\Db; 
use app\common\model\LogOrderModel as lo;
use think\Queue;
class GtourOrderModel extends Model
{
    // 确定链接表名
    protected $name = 'gtour_order';
    /**
     * 根据搜索条件获取所有的跟团订单数据
     * @param $where  查询条件
     * @param $offset
     * @param $limit
     * @return mixed
     */
    public function getGtourOrderList($where ,$offset, $limit)
    {
        $resultData = $this
            ->alias('go')
            ->join('group_tour gt','go.gtour_id=gt.id','left')
            ->where($where)
            ->field('go.order_id,go.commission_fee,go.order_sn,gt.gtour_title,go.gtour_id,go.user_id,go.linkman,go.tel,go.gtour_number,go.gtour_start,
                    go.order_price,go.procedure_fee,go.order_status,go.pay_type,go.is_pay,go.is_appraise,go.is_refund,
                    go.order_unique,go.is_del,go.create_time')
            ->order('order_id desc')
            ->limit($offset, $limit)
            ->select(); 
        if(count($resultData)>0)
        {
            foreach ($resultData as $key => $v)
            {
                $resultData[$key]['order_status'] = lvOrderStatus($v['order_status']);
                $resultData[$key]['pay_type'] = lvPayType($v['pay_type']);
                $resultData[$key]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
            }
        }
        return $resultData;
    }


    /**
     * 根据搜索条件获取所有的跟团订单数量
     * @param $where  查询条件
     * @return mixed
     */
    public function  getGtourOrderCount($where)
    {
            return $this
            ->alias('go')
            ->join('group_tour gt','go.gtour_id=gt.id','left')
            ->where($where)
            ->count();
    }

    /**根据搜索条件获取单条的跟团游订单信息
     * @param $where 查询条件
     * @return mixed
     */
    public function  getGtourOrderById($where)
    {
        $resultData = $this
        ->alias('go')
        ->join('group_tour gt','go.gtour_id=gt.id','left')
        ->join('team t','t.team_id = gt.team_id','left')
        ->where($where)
        ->field('go.order_id,gt.team_id,team_name,go.order_sn,gt.gtour_title,go.gtour_id,go.user_id,go.linkman,go.tel,go.gtour_number,go.gtour_start,
                    go.order_price,go.order_status,go.pay_type,go.is_pay,go.is_appraise,go.is_refund,
                    go.order_unique,go.is_del,go.create_time')
        ->order('order_id desc')
        ->find();
        if(empty($resultData)) return [];
        $resultData['pay_type'] = lvPayType($resultData['pay_type']);
        $resultData['order_status'] = lvOrderStatus($resultData['order_status']);
        $resultData['create_time'] = date('Y-m-d H:i:s',$resultData['create_time']);
        return $resultData;
    }

   public function submitGtourOrder(){ 
     $gt_id = input('post.gt_id');
       if(empty($gt_id))
         return apiReturn('400','跟团游id为空',0); 
     $linkman = input('post.linkman');
       if(empty($linkman))
         return apiReturn('400','联系人姓名为空',0);
     $tel = input('post.tel');
       if(empty($tel))
         return apiReturn('400','联系人电话为空',0);
     $gtour_number = input('post.gtour_number');
       if(empty($gtour_number))
         return apiReturn('400','参团人数为空',0);
     $tg_date = input('post.gtour_start');
       if(empty($tg_date))
         return apiReturn('400','开团日期为空',0); 
      $user_id = input('post.uid');
       if(empty($user_id))
         return apiReturn('400','用户信息为空',0);  
      //查看旅行社是否有该团
      $grouptour = Db::name('group_tour')
      ->alias('gt')
      ->field('gt.id,gg.tg_date,t.team_name,gt.team_id,tg_price,gt.gtour_title')
      ->join('team t','t.team_id=gt.team_id','left')
      ->join('gtour_gschedule gg','gg.tg_id=gt.id','left')
      ->where(['gt.id'=>$gt_id,'gt.is_del'=>0,'gt.is_display'=>0,'t.is_pass'=>1,'t.is_del'=>0,'gg.tg_date'=>$tg_date]) 
      ->find();   
       if(empty($grouptour))
         return apiReturn('400','无该团信息',0); 
     //查看是否有该开团日期 
       $resDate = Db::name('gtour_gschedule')
       ->where(['tg_id'=>$gt_id,'tg_date'=>$tg_date])
       ->find();
       if(empty($resDate))
         return apiReturn('400','无该日期跟团信息',0);
     //生成订单
      Db::startTrans();
      try{
        $orderSn = makeOrderSn(); 
           //计算该旅行社的订单佣金
        $commissionRate = Db::name('team') 
        ->where(['is_del'=>0,'is_pass'=>1,'team_id'=>$grouptour['team_id']])
        ->value("commission_rate");
        if(empty($commissionRate))
          $commissionRate = 0;  
        //创建订单
        $order['order_sn'] = $orderSn;
        $order['team_id'] = $grouptour['team_id'];
        $order['gtour_id'] = $grouptour['id'];
        $order['user_id'] = $user_id;
        $order['linkman'] = $linkman;
        $order['tel'] = $tel;
        $order['gtour_number'] = $gtour_number;
        $order['gtour_start'] = strtotime($tg_date);
        $order['commission_rate'] = $commissionRate;
        $order['order_price'] = $gtour_number * $grouptour['tg_price'];
        $order['total_price'] = $grouptour['tg_price'];
        $order['create_time'] = time();
        $order['cancel_code'] = 'team_cancle_code_'.getRandNumber();
        $result = $this->isUpdate(false)->save($order);  
        if(false !== $result)
        {
           //需要给用户返回的信息
            $orderInfo['order_sn'] = $order['order_sn'];
            $orderInfo['team_id'] = $grouptour['team_id'];
            $orderInfo['gtour_id'] = $grouptour['id'];
            $orderInfo['gtour_title'] = $grouptour['gtour_title'];
            $orderInfo['tg_date'] = $grouptour['tg_date'];
            $orderInfo['gtour_number'] =  $gtour_number;
            $orderInfo['price'] = $order['order_price']; 
            $orderId = $this->order_id; 
                        //半个小时未付款取消订单
           $jobHandlerClassName = 'app\api\job\Cancelorder';
           $jobQueueName = 'Cancel';
           $jobData = [
                      'type'=>3, 
                      'order_id'=>$orderId,  
                    ]; 
           $isPushed = Queue::later(1800,$jobHandlerClassName , $jobData , $jobQueueName);
            //创建订单记录 
            $logOrder = new lo();
            $logOrder->addLogOrder($orderId,3 ,$user_id, 0, '下单成功，等待用户付');
            //销售量+$gtour_number
            Db::name('group_tour')->where('id',$gt_id)->setInc('sale_sum',$gtour_number);
             //给用户发送消息提示 1景点订单 2酒店订单 3旅行社订单
            send_user_message(3, 2, $user_id, $orderSn,$grouptour['gtour_title'],$orderId,3);
            //给商户发送消息
            
        } 
         Db::commit();
         return apiReturn('200','提交订单成功',$orderInfo);  
      }catch(\Exection $e)
      { 
          Db::rollback();
          return apiReturn('400','提交订单失败',0); 
      }
   }

}